/*
 * Copyright © 2009 Gerald Isaac Schwarz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package base;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.UIManager;

public class GamePlayer extends GUI {
	private Engine engine;
	private JFileChooser fileChooser = new JFileChooser();
	private JMenuItem mapEditor;
	
	private ActionListener menuListener = new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals(mapEditor.getActionCommand())) {
				new MapEditor(getBoardWidget().getBoard());
				dispose();
			}
		}
		
	};
	
	private TurnListener turnListener = new TurnListener() {

		@Override
		public void turnPerformed(TurnEvent turnEvent) {
			if (getEngine().getBoard().getPlayers().size() > 1) {
				displayMessage(getEngine().getBoard().getCurrentPlayer().getName() + ", it's your turn.");
			}
			else {
				displayMessage(getEngine().getBoard().getCurrentPlayer().getName() + " wins!");
			}
		}
		
	};
	
	public GamePlayer() {
		super();
		this.initialize();
		this.newGame();
	}
	
	public GamePlayer(Board board) {
		super();
		this.initialize();
		this.setBoardWidget(new BoardWidget(board));
	}
	
	public void initialize() {
		this.mapEditor = new JMenuItem("Map Editor");
		
		this.mapEditor.setActionCommand("Map Editor");
		
		this.mapEditor.addActionListener(this.menuListener);
		
		super.editMenu.add(this.mapEditor);
		
		this.mapEditor.setMnemonic(KeyEvent.VK_M);
		
		this.displayMessage("Please load a game to start playing.");
		
		this.setTitle("Stones Game");
		this.setVisible(true);
	}
	
	protected Engine getEngine() {
		return this.engine;
	}
	
	@Override
	protected void move(Point destination) {
		if (!this.isSelectedPiece() || !this.getEngine().move(this.getSelectedPiece(), destination)) {
			this.displayMessage("Invalid move. The current player is " + getEngine().getBoard().getCurrentPlayer().getName());
		}
		else {
			this.getBoardWidget().setFocusedSquare(destination);
			this.getBoardWidget().setHightlightTargets(null);
			this.getBoardWidget().setSelectedSquare(null);
			this.setSelectedPiece(null);
		}
		
		this.refresh();
	}
	
	@Override
	protected void select(Square square) {
		if (square != null) {
			this.getBoardWidget().setFocusedSquare(square.getLocation());
			Piece piece = this.getEngine().getBoard().getPiece(square.getLocation());
			this.setSelectedPiece(piece);
			
			if (piece != null) {
				Point[][] points = this.getEngine().getMoves(this.getSelectedPiece());
				this.getBoardWidget().setHightlightTargets(points);
				this.getBoardWidget().setSelectedSquare(square.getLocation());
			}
			else {
				this.getBoardWidget().setSelectedSquare(null);
				this.getBoardWidget().setHightlightTargets(null);
			}
		}
		else {
			this.getBoardWidget().setSelectedSquare(null);
			this.getBoardWidget().setHightlightTargets(null);
			this.setSelectedPiece(null);
		}
		
		this.refresh();
	}
	
	@Override
	protected boolean isSelectedPiece() {
		return this.getSelectedPiece() != null && 
		this.getEngine().getBoard().getCurrentState(this.getSelectedPiece()).getOwner() == this.getEngine().getBoard().getCurrentPlayer();
	}
	
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception e) {}
		
		if (args.length == 0) {
			new GamePlayer();
		}
		else if (args.length == 1) {
			GameLoader gameLoader = new GameLoader(GamePlayer.getInputStream("templates/2x12_8x8.xml"));
			
			new GamePlayer(gameLoader.getEngine().getBoard());
		}
	}
	
	@Override
	protected void newGame() {
		try {
			File templateFile = new File(this.getTemplateFolder() + this.getFileSeparator() + "2x12_8x8.xml");
			
			if (!templateFile.exists()) {
				GameLoader gameLoader = new GameLoader(GamePlayer.getInputStream("templates/2x12_8x8.xml"));
				
				new GameSaver(gameLoader.getEngine().getBoard(), templateFile);
			}
			
			GameLoader gameLoader = new GameLoader(templateFile);
			
			NewGameConfigurator configurator = new NewGameConfigurator(gameLoader, this);
			
			if (configurator.isResult()) {
				this.engine = configurator.getEngine();
				this.engine.addTurnListener(this.turnListener);
				this.setBoardWidget(new BoardWidget(this.engine.getBoard()));
				this.displayMessage(getEngine().getBoard().getCurrentPlayer().getName() + ", it's your turn.");
			}
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}
	}
	
	@Override
	protected void open() {
		int result = this.fileChooser.showOpenDialog(this);
		
		if (result == JFileChooser.APPROVE_OPTION) {
			this.engine = new GameLoader(this.fileChooser.getSelectedFile()).getEngine();
			this.engine.addTurnListener(this.turnListener);
			this.setBoardWidget(new BoardWidget(this.engine.getBoard()));
			this.displayMessage(getEngine().getBoard().getCurrentPlayer().getName() + ", it's your turn.");
		}
	}
	
	@Override
	protected void save() {
		if (this.getEngine() != null) {
			int result = this.fileChooser.showSaveDialog(this);
			
			if (result == JFileChooser.APPROVE_OPTION) {
				new GameSaver(this.getEngine().getBoard(), this.fileChooser.getSelectedFile());
			}
		}
		else {
			this.displayMessage("There is no game to save!");
		}
	}
}